package com.situ.blog.controller;

import com.situ.blog.pojo.entity.Auth;
import com.situ.blog.pojo.entity.User;
import com.situ.blog.pojo.query.UserQuery;
import com.situ.blog.service.IAuthService;
import com.situ.blog.service.IUserService;
import com.situ.blog.service.impl.AuthServiceImpl;
import com.situ.blog.service.impl.UserServiceImpl;
import com.situ.blog.util.*;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/user")
public class UserController extends BaseController {
    private IUserService userService = new UserServiceImpl();
    private IAuthService authService = new AuthServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");
        switch (method){
            case "login"://登录、权限管理
                login(req,resp);
                break;
            case "logout"://注销(退出)，重新回到登录界面
                logout(req,resp);
                break;
            case "selectByPage"://分页，查询(name模糊查询)
                selectByPage(req,resp);
                break;
            case "deleteById"://单个元素的删除
                deleteById(req,resp);
                break;
            case "deleteAll"://批量删除
                deleteAll(req,resp);
                break;
            case "add"://添加：账号、密码、权限等级、上传头像
                add(req,resp);
                break;
            case "selectById"://查询id，用于编辑回显数据
                selectById(req,resp);
                break;
            case "update"://编辑更新数据
                update(req,resp);
                break;
            case "updateStatus": //根据状态，做用户登录是否禁用
                updateStatus(req,resp);
                break;
                
        }
    }

    private void updateStatus(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        String status = req.getParameter("status");
        userService.updateStatus(Integer.parseInt(id),Integer.parseInt(status));
        toJSON(resp,Result.ok("更新成功"));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.update");
        User user = MyBeanUtils.copyToBean(req,User.class);
        userService.update(user);

        toJSON(resp,Result.ok("更新成功"));
    }

    private void selectById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.selectById");
        String id = req.getParameter("id");
        User user = userService.selectById(Integer.parseInt(id));

        toJSON(resp,Result.ok(user));

    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.add");

        User user = MyBeanUtils.copyToBean(req,User.class);
        userService.add(user);
        toJSON(resp, Result.ok("添加成功"));
    }

    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.deleteAll");
        String[] ids = req.getParameterValues("ids[]");
        userService.deleteAll(ids);
        toJSON(resp, Result.ok("删除成功"));
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.deleteById");
        String id = req.getParameter("id");
        userService.deleteById(Integer.parseInt(id));

        toJSON(resp, Result.ok("删除成功"));
    }

    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserServlet.selectByPage");

        UserQuery userQuery = MyBeanUtils.copyToBean(req,UserQuery.class);
        PageInfo pageInfo = userService.selectByPage(userQuery);

        toJSON(resp,pageInfo);

    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.logout");
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        session.removeAttribute("auths");

        //CookieUtils自建工具类的方法必须为静态方法，要不然引用CookieUtils无法找到方法
        Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
        //退出后，清除cookie记录，方法：创建相同名称的cookie(把原有的cookie覆盖)，并设置为0
        //如果用户没有勾选自动登录，那么这个Cookie就是null,回报空指针异常，所以要加判断
        if (cookie != null){
            //设置Cookie的存活时间为0
            cookie.setMaxAge(0);
            //退出后重新登录，则重新添加cookie
            resp.addCookie(cookie);
        }

        toJSON(resp,Result.ok("退出成功"));
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        String regexName = "^[a-zA-Z0-9_\\u4e00-\\u9fa5\\s·]+$";
        Pattern pattern = Pattern.compile(regexName);
        Matcher matcher = pattern.matcher(name);
        if (!matcher.find()){
            JSONUtils.toJSON(resp,Result.error("用户名不能有特殊字符"));
            return;
        }


        //先判断验证码是不是正确
        //1、验证码错误，返回一个验证码错误的提示
        //2、验证码正确，再验证 验证码是不是正确
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)){
            toJSON(resp, Result.error("验证码错误"));
            return;
        }

        User user = userService.login(name,password);
        //使用ajax改进登录
        if (user == null){
            toJSON(resp,Result.error("用户名或者密码错误"));
            return;
        }
        if (user.getStatus() == 0){
            toJSON(resp,Result.error("该用户已被禁用，请联系管理员"));
            return;
        }

        //自动登录
        //判断有没有勾选自动登录
        String autoLogin = req.getParameter("autoLogin");
        if (!ObjectUtils.isEmpty(autoLogin)){
            Cookie cookie = new Cookie("autoLogin", user.getName() + "&" + user.getPassword());
            //设置Cookie的存活时间和绑定路径
            cookie.setMaxAge(60*60*24*7); //设置时间为1周
            cookie.setPath(req.getContextPath());
            //在响应resp中添加cookie,返回给浏览器
            resp.addCookie(cookie);
        }


        session.setAttribute("user",user);
        //权限管理，必须打开过滤器，每次登录成功，才能显示遍历各个模块
        List<Auth> auths = authService.selectByRole(user.getRole());
        session.setAttribute("auths",auths);
        toJSON(resp,Result.ok("登录成功"));

    }
}
